package panda.query.util;

import java.util.List;

import panda.query.scan.Scanner;
import panda.query.scan.TableScanner;
import panda.query.scan.UpdatableScanner;
import panda.query.struct.Attribute;
import panda.record.Schema;
import panda.record.TableToken;
import panda.transaction.Transaction;

/**
 * 
 * @author Tian Yuan
 */
public class TempTable {
	private static int id = 0;
	private TableToken tt;
	private Transaction tx;
	
	/**
	 * 
	 * @param s
	 */
	public TempTable(Schema s, Transaction tx) {
		String tblname = getTempTableName();
		this.tx = tx;
		tt = new TableToken(tblname, s);
	}
	
	/**
	 * 
	 * @param s
	 */
	public void copyFrom(Scanner s) {
		UpdatableScanner selfScan = open();
		
		while (s.next()) {
			selfScan.insert();
			for (Attribute a : tt.getSchema().getAllAttributes()) {
//				System.out.println(s.getValue(a).getContentValue());
				selfScan.setValue(a, s.getValue(a));
			}
		}
		
		selfScan.close();
		s.close();
	}
	
	/**
	 * 
	 * @return
	 */
	public UpdatableScanner open() {
		return new TableScanner(tt, tx);
	}
	
	/**
	 * Sort the contents in this table in ascending order
	 * @param attrs by which columns to sort
	 */
//	public void sort(List<Attribute> attrs) {
//		MergeSorter.sortTable(tt, attrs, new GroupByComparator(attrs), tx);
//	}
	
//	public void sort(List<Attribute> attrs, List<Boolean> order) {
//		MergeSorter.sortTable(tt, attrs, new OrderByComparator(attrs, order), tx);
//	}
	
	public TableToken getTableInfo() {
		return tt;
	}
	
	private static synchronized String getTempTableName() {
		return "~tmptbl" + (id ++);
	}
}
